package com.hmall.api.fallback;

import com.hmall.api.client.ItemClient;
import com.hmall.api.dto.ItemDTO;
import com.hmall.api.dto.OrderDetailDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.openfeign.FallbackFactory;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;

/**
 * 商品服务降级处理类
 * 当如果调用 ItemClient对象的对应方法的时候；如果触发了熔断（异常、失败、慢调用等比例达到阈值）而走降级逻辑
 */
@Component
@Slf4j
public class ItemClientFallbackFactory implements FallbackFactory<ItemClient> {
    @Override
    public ItemClient create(Throwable cause) {
        return new ItemClient() {
            @Override
            public List<ItemDTO> queryItemByIds(Collection<Long> ids) {
                log.error("查询商品信息失败；执行了ItemClientFallbackFactory.queryItemByIds；查询的商品id为：" + ids, cause);
                //如果远程调用失败的话；返回空集合
                return List.of();
            }

            @Override
            public void deductStock(List<OrderDetailDTO> items) {
                log.error("扣减库存失败；执行了ItemClientFallbackFactory.deductStock。扣减的订单明细为：" + items, cause);
            }

            @Override
            public ItemDTO queryItemById(Long id) {
                log.error("远程调用ItemClient#queryItemById方法出现异常：" + id, cause);
                return null;
            }
        };
    }
}
